package jd.se.register;

import com.alibaba.fastjson.JSON;
import jd.se.common.CurrentUser;
import jd.se.common.Result;
import jd.se.common.Utils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.CharArrayWriter;
import java.io.IOException;
import java.io.Reader;

@WebServlet("/register")
public class registerAPI extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        try{
            req.setCharacterEncoding("UTF-8");

            Reader reader = req.getReader();
            CharArrayWriter out = new CharArrayWriter();

             try {
                 char[] charBuff = new char[1024];
                 int len = -1;

                 while ((len = reader.read(charBuff)) != -1) {
                    out.write(charBuff, 0, len);
                }
                 out.flush();

                 String  json = out.toString();

                 registerDto dto = JSON.parseObject(json,registerDto.class);

                 boolean che = new checkService().registerCHE(dto);
                 if(che){
                     Utils.outResult(resp, Result.fail(Result.ERR_CODE_BUSINESS, "该学号已经被注册！"));
                 }
                 else{
                     boolean ok= new registerSer().registerADD(dto);
                     if(ok) Utils.outResult(resp, Result.success("账号注册成功！"));
                 }
             }finally {
            out.flush();
            out.close();
            reader.close();
             }
        }catch (Exception e){
            Utils.outResult(resp,Result.fail(500,"系统升级中......!"));
            e.printStackTrace();
        }


    }
}
